package com.ricohgag.controller.admin;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ricohgag.entity.ShopOrder;
import com.ricohgag.entity.VipUser;
import com.ricohgag.entity.custom.ShopOrderVo;
import com.ricohgag.service.ShopOrderService;
import com.ricohgag.service.VipUserService;
import com.ricohgag.util.Msg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 肖晖
 * @since 2018-08-25
 */
@Controller
@RequestMapping("/admin/order")
public class ShopOrderController {
    @Autowired
    private ShopOrderService shopOrderService;
    @Autowired
    private VipUserService vipUserService;

    @RequestMapping("/index")
    public ModelAndView toShopOrderIndex(String orderSn, @RequestParam(value = "pageNow", required = false) Integer current, HttpServletRequest request) throws Exception{
        ModelAndView mav = new ModelAndView("admin/order/index");
        String url = "/admin/order/index";

        if(current == null){
            current = 1;
        }
        Page<ShopOrder> page = new Page<>(current, 10);

        List<ShopOrderVo> orderGoodsVoList = shopOrderService.selectOrder(orderSn, page);
        System.err.println("shopOrderVoList:"+orderGoodsVoList.size());
        mav.addObject("orderSn",orderSn);
        mav.addObject("orderGoodsVoList", orderGoodsVoList);
        mav.addObject("pages", page.getPages());
        mav.addObject("url",url);

        return mav;
    }

    @RequestMapping("/orderCancel")
    @ResponseBody
    public Msg cancel(Integer orderId) throws Exception{
        System.out.println("orderId:"+orderId);
        Msg msg = new Msg();
        boolean flag = shopOrderService.updateStatusById(orderId, -1);
        ShopOrder order = shopOrderService.selectOrderById(orderId);


        if(flag){
            //取消订单时，退款
            VipUser vipUser = vipUserService.selectVipUserOne(order.getUserId());
            vipUser.setRechargeMoney(order.getTotalMoney());
            vipUserService.updateVipUser(vipUser);

            msg.setStatus(1);
            msg.setMsg("取消订单成功");
        } else {
            msg.setStatus(0);
            msg.setMsg("取消订单失败");
        }
        return msg;
    }

    @RequestMapping("/orderConfirm")
    @ResponseBody
    public Msg orderConfirm(Integer orderId){
        Msg msg = new Msg();
        boolean flag = shopOrderService.updateStatusById(orderId, 2);
        if(flag){
            msg.setMsg("确认订单成功");
        } else {
            msg.setMsg("确认订单失败");
        }
        return msg;
    }



}

